package morm

import (
	"api/libs/orm"
	"gitee.com/dreamwood/ez"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"strings"
	"time"
)

//type QueryBuilder struct {
//	Conditions map[string]interface{} `json:"_where"`
//	Order      []string               `json:"_order"`
//	Page       int                    `json:"page"`
//	Limit      int                    `json:"limit"`
//}

func NewQueryBuilder() *orm.HttpQuery {
	return &orm.HttpQuery{
		Conditions: make(map[string]interface{}),
		Order:      make([]string, 0),
		Page:       -1,
		Limit:      -1,
	}
}

func CreateFilter(filters map[string]interface{}) bson.D {
	//re := make(map[string]interface{})
	prepare := make(map[string][]bson.E)
	direct := make(bson.D, 0)
	for key, filter := range filters {
		var value interface{}
		finds := strings.Split(key, "__")
		last := finds[len(finds)-1]
		//检查是否包含了特定的关键词
		//hasSuffix := 0
		if ez.IsInArray([]interface{}{"gt", "gte", "lt", "lte", "in", "nin", "eq", "ne", "exists", "near", "regex"}, last) > -1 {
			//hasSuffix = 1
			key = strings.ReplaceAll(key, "__"+last, "")
			value = ez.StringKeyMap{"$" + last: filter}
			key = strings.ReplaceAll(key, "__", ".")
			if strings.HasSuffix(key, "At") {
				switch filter.(type) {
				case string:
					filter, _ = time.Parse(time.RFC3339, filter.(string))
					break
				case time.Time:

					break
				case int64, int, uint:
					//todo 考虑长度
					break
				default:
					println("位置时间类型")
				}

				prepare[key] = append(prepare[key], bson.E{"$" + last, filter})
			} else {
				prepare[key] = append(prepare[key], bson.E{"$" + last, filter})
			}
		} else {
			if key == "id" {
				key = "_id"
				value = bson.E{"$oid", value}
			} else {
				value = filter
			}
			key = strings.ReplaceAll(key, "__", ".")
			direct = append(direct, bson.E{key, value})
		}
		//re[key] = value
	}
	for key, v := range prepare {
		direct = append(direct, bson.E{key, v})
	}
	return direct
}

func CreateOption(orderby []string, offset int, limit int) *options.FindOptions {
	//tool.JsonLog(orderby)
	//处理排序数据
	realOrderBy := bson.D{}
	for _, str := range orderby {
		if str[0:1] == "-" || str[0:1] == "_" {
			realOrderBy = append(realOrderBy, bson.E{str[1:], -1})
		} else {
			realOrderBy = append(realOrderBy, bson.E{str, 1})

		}
	}
	opt := options.FindOptions{}
	//tool.JsonLog(realOrderBy)
	return opt.SetLimit(int64(limit)).SetSkip(int64(offset)).SetSort(realOrderBy)
}

func CreateFindOneOption(orderby []string) *options.FindOneOptions {
	//处理排序数据
	realOrderBy := bson.D{}
	for _, str := range orderby {
		if str[0:1] == "-" || str[0:1] == "_" {
			realOrderBy = append(realOrderBy, bson.E{str[1:], -1})
		} else {
			realOrderBy = append(realOrderBy, bson.E{str, 1})
		}
	}
	opt := options.FindOneOptions{}

	return opt.SetSort(realOrderBy)
}
